#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * Description: RSA加密工具类
 *
 * @author songcx
 * @date 2020/6/28 17:30
 *
 * <pre>
 *              ${copyright}
 *      Copyright (c) 2019. All Rights Reserved.
 * </pre>
 */
@Slf4j
public class RsaUtil {

	private static Map<String, String> keyMap = new HashMap<>();

	/**
	 * Description:获取密钥对
	 * <>
	 *
	 * @author songcx
	 * @date 17:31 2020/6/28
	 **/
	private static void getKeyPair() throws Exception {
		//KeyPairGenerator类用于生成公钥和密钥对，基于RSA算法生成对象
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
		//初始化密钥对生成器，密钥大小为96-1024位
		keyPairGen.initialize(1024, new SecureRandom());
		//生成一个密钥对，保存在keyPair中
		KeyPair keyPair = keyPairGen.generateKeyPair();
		//得到私钥
		PrivateKey privateKey = keyPair.getPrivate();
		//得到公钥
		PublicKey publicKey = keyPair.getPublic();
		//得到公钥字符串
		String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
		//得到私钥字符串
		String privateKeyString = new String(Base64.encodeBase64(privateKey.getEncoded()));
		//将公钥和私钥保存到Map
		keyMap.put("public", publicKeyString);
		keyMap.put("private", privateKeyString);
	}


	public static String decrypt(String str) throws Exception {
		//Base64解码加密后的字符串
		byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
		//Base64编码的私钥
		byte[] decoded = Base64.decodeBase64(RsaUtil.getKey("private"));
		PrivateKey priKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
		//RSA解密
		String outStr = null;
		try {
			Cipher cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.DECRYPT_MODE, priKey);
			outStr = new String(cipher.doFinal(inputByte));
		} catch (Exception e) {
			log.error(e.getMessage());
			log.error("密码解密失败");
		}
		return outStr;
	}

	public static String getKey(String key) throws Exception {
		if (RsaUtil.keyMap.isEmpty()) {
			RsaUtil.getKeyPair();
		}
		return RsaUtil.keyMap.get(key);
	}

}
